package com.xuelang.pipeline.infrastructure.project.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuelang.pipeline.client.common.exception.BizException;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.project.dto.ProjectQuery;
import com.xuelang.pipeline.client.project.enums.ProjectStatus;
import com.xuelang.pipeline.domain.project.Project;
import com.xuelang.pipeline.domain.project.repository.ProjectRepository;
import com.xuelang.pipeline.infrastructure.project.converter.ProjectToDOConverter;
import com.xuelang.pipeline.infrastructure.project.dataobject.ProjectDO;
import com.xuelang.pipeline.infrastructure.project.mapper.ProjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>项目仓库实现类</p>
 *
 * @author : yixin.lys
 * @date : 2024-09-02 16:35
 **/
@Repository
public class ProjectRepositoryImpl implements ProjectRepository {

    @Autowired
    private ProjectMapper mapper;

    @Override
    public PageRecord<Project> pageProjects(long currentPage, long pageSize, ProjectQuery projectQuery) {
        currentPage = Math.max(currentPage, 1);
        pageSize = Math.max(pageSize, 10);

        Page<ProjectDO> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<ProjectDO> wrapper = Wrappers.lambdaQuery(ProjectDO.class);

        wrapper.eq(StringUtils.isNotBlank(projectQuery.getProjectName()), ProjectDO::getProjectName, projectQuery.getProjectName());
        wrapper.eq(StringUtils.isNotBlank(projectQuery.getProjectCode()), ProjectDO::getProjectCode, projectQuery.getProjectCode());
        wrapper.eq(projectQuery.getProjectType() != null, ProjectDO::getProjectType, projectQuery.getProjectType());
        wrapper.eq(StringUtils.isNotBlank(projectQuery.getProjectLeader()), ProjectDO::getProjectLeader, projectQuery.getProjectLeader());
        wrapper.eq(projectQuery.getStatus() != null, ProjectDO::getStatus, projectQuery.getStatus());
        wrapper.apply(projectQuery.getStartTime() != null, "CREATE_TIME >= {0}", projectQuery.getStartTime());
        wrapper.apply(projectQuery.getEndTime() != null, "CREATE_TIME <= {0}", projectQuery.getEndTime());

        wrapper.orderByDesc(ProjectDO::getCreateTime);

        Page<ProjectDO> pageResult = mapper.selectPage(page, wrapper);
        if (Objects.nonNull(pageResult)) {
            return new PageRecord<>(
                    pageResult.getCurrent(),
                    pageResult.getSize(),
                    pageResult.getTotal(),
                    pageResult.getPages(),
                    pageResult.getRecords().stream().map(ProjectToDOConverter.INSTANCE::fromDO).collect(Collectors.toList())
            );
        }
        return null;
    }

    @Override
    public Integer createProject(Project project) {
        // 检查项目名称是否已存在
        LambdaQueryWrapper<ProjectDO> nameCheckWrapper = Wrappers.lambdaQuery(ProjectDO.class)
                .eq(ProjectDO::getProjectName, project.getProjectName());
        if (mapper.selectCount(nameCheckWrapper) > 0) {
            throw new BizException("项目名称已存在");
        }

        // 检查项目编号是否已存在
        LambdaQueryWrapper<ProjectDO> codeCheckWrapper = Wrappers.lambdaQuery(ProjectDO.class)
                .eq(ProjectDO::getProjectCode, project.getProjectCode());
        if (mapper.selectCount(codeCheckWrapper) > 0) {
            throw new BizException("项目编号已存在");
        }
        // 新增默认设置为未开始
        project.setStatus(ProjectStatus.NOT_START.ordinal());
        ProjectDO projectDO = ProjectToDOConverter.INSTANCE.toDO(project);
        int rows = mapper.insert(projectDO);
        return rows > 0 ? projectDO.getId() : null;
    }

    @Override
    public boolean deleteProjectById(Integer id) {
        // 根据项目ID删除项目
        return mapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateProject(Project project) {
        // 检查其他项目是否已存在相同的名称
        LambdaQueryWrapper<ProjectDO> nameCheckWrapper = Wrappers.lambdaQuery(ProjectDO.class)
                .eq(ProjectDO::getProjectName, project.getProjectName())
                .ne(ProjectDO::getId, project.getId());
        if (mapper.selectCount(nameCheckWrapper) > 0) {
            throw new BizException("项目名称已存在");
        }

        // 检查其他项目是否已存在相同的编号
        LambdaQueryWrapper<ProjectDO> codeCheckWrapper = Wrappers.lambdaQuery(ProjectDO.class)
                .eq(ProjectDO::getProjectCode, project.getProjectCode())
                .ne(ProjectDO::getId, project.getId());
        if (mapper.selectCount(codeCheckWrapper) > 0) {
            throw new BizException("项目编号已存在");
        }

        // 更新项目信息
        ProjectDO projectDO = ProjectToDOConverter.INSTANCE.toDO(project);
        return mapper.updateById(projectDO) > 0;
    }

    @Override
    public Project findProjectById(Integer id) {
        // 根据ID查询项目
        ProjectDO projectDO = mapper.selectById(id);
        // 将 ProjectDO 转换为 Project 实体
        return ProjectToDOConverter.INSTANCE.fromDO(projectDO);
    }

    @Override
    public Project findProjectByCode(String code) {
        LambdaQueryWrapper<ProjectDO> wrapper = Wrappers.lambdaQuery(ProjectDO.class);
        wrapper.eq(ProjectDO::getProjectCode, code);

        return ProjectToDOConverter.INSTANCE.fromDO(mapper.selectOne(wrapper));
    }

    @Override
    public List<Project> findAllProjects() {
        // 查询所有项目
        List<ProjectDO> projectDOList = mapper.selectList(null);
        if(CollectionUtils.isNotEmpty(projectDOList)) {
            // 将 ProjectDO 列表转换为 Project 实体列表
            return projectDOList.stream().map(ProjectToDOConverter.INSTANCE::fromDO).collect(Collectors.toList());
        }
        return null;
    }
}
